import { showLoading, showError, closeLoading } from "@/utils/vant";
import { queryDrawVid } from "@/api/drawVid";
interface Params {
  page?: number;
  size?: number;
}
interface DrawVidItem {
  youtubeId: string;
}

const useDrawVid = defineStore("drawVid", () => {
  const loading = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  const videoList = ref<DrawVidItem[]>([]);
  const total = ref(0);
  const params = reactive<Params>({
    page: 1,
    size: 20
  });
  function reset() {
    params.page = 1;
    params.size = 20;
    total.value = 0;
    videoList.value = [];
    finished.value = false;
    refreshing.value = false;
    loading.value = true;
  }
  async function fetchData() {
    try {
      showLoading();
      const res = await queryDrawVid(params);
      const pList = res.data.list.map((item: any) => {
        const youtubeId = item.youtube_url?.match(/v=([^&]+)/)?.[1] || "";
        return { ...item, youtubeId };
      });
      videoList.value = videoList.value.concat(pList);
      if (params.page === 1) {
        total.value = res.data.total;
      }
      if (unref(videoList).length >= total.value) {
        finished.value = true;
      }
    } catch (error) {
      showError(error);
    } finally {
      loading.value = false;
      closeLoading();
    }
  }
  const onLoad = () => {
    if (unref(videoList).length) {
      params.page = (params.page || 1) + 1;
    }
    fetchData();
  };

  const onRefresh = () => {
    reset();
    onLoad();
  };
  return {
    videoList,
    loading,
    finished,
    refreshing,
    onLoad,
    onRefresh
  };
});
export const useDrawVidRefs = () => {
  return storeToRefs(useDrawVid());
};
export default useDrawVid;
